const resWrite = require('./response');
/**
 * response a JSON
 * @param options
 * @param callback
 */
function main(options,callback){
  let response = options.response;
  let data = options.data;
  let cookies = options.cookies;
  new Promise((resolve,reject)=>{
    response ? resolve() : reject();
  }).then(
      //have response
      ()=>{
        new Promise((resolve,reject)=>{
          try{
            JSON.stringify(data) !== undefined && JSON.stringify(data) !== "null" ? resolve() : reject();
          }catch(error){
           reject(error);
          }
        }).then(
            //have JSON
            ()=>{
              resWrite({
                response: response,
                statusCode: 200,
                mimeKey: 'JSON',
                dataType: 'string',
                cookies: cookies,
                data:JSON.stringify(data)
              }, callback);
            }
            //have no JSON
            ,(error)=>{
              !error ? callback(new SyntaxError("JSON can't be undefined or null"),null) : callback(new SyntaxError('JSON format error'),null);
            }
        )
      }
      //have no response
      ,()=>{
        callback(new SyntaxError("response can't be undefined or null"),null);
      }
  ).catch((error)=>{
    callback(error,null);
  })
}

module.exports=main;